package ru.averta.notes.service.security;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl;
import org.springframework.security.acls.domain.SidRetrievalStrategyImpl;
import org.springframework.security.acls.model.AccessControlEntry;
import org.springframework.security.acls.model.MutableAcl;
import org.springframework.security.acls.model.MutableAclService;
import org.springframework.security.acls.model.NotFoundException;
import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.acls.model.Sid;
import org.springframework.security.acls.model.SidRetrievalStrategy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import ru.averta.notes.domain.User;
import ru.averta.notes.service.security.login.SecurityUser;

@Service
public class SecurityServiceImpl implements SecurityService {

	public SecurityContext getSecurityContext() {
		return SecurityContextHolder.getContext();
	}

	public void setSecurityContext(SecurityContext securityContext) {
		SecurityContextHolder.setContext(securityContext);
	}

	public String getCurrentUserName() {
		Authentication auth = getAuthentication();
		if(auth == null || auth.getPrincipal() == null)
			return null;
		if(auth.getPrincipal() instanceof UserDetails)
			return ((UserDetails)auth.getPrincipal()).getUsername();
		else
			return auth.getPrincipal().toString();
	}

	public boolean isLoggedIn() {
		//return (!getCurrentUserName().equals(""));

		if (getSecurityContext() == null) {
			return false;
		} else if (getSecurityContext().getAuthentication() == null) {
			return false;
		} else if (!getSecurityContext().getAuthentication().isAuthenticated()) {
			return false;
		} else {
			return true;
		}
	}

	private Authentication getAuthentication() {
		return getSecurityContext().getAuthentication();
	}

	public User getCurrentUser() {
		if (isLoggedIn()) { 
			SecurityUser securityUser = (SecurityUser) getSecurityContext().getAuthentication().getPrincipal();
			return securityUser.getUser();
		} else {
			return null;
		}
	}

}
